//
//  TrainViewController.m
//  TingLiFeng
//
//  Created by xinxuan on 16/1/3.
//  Copyright © 2016年 xinxuan. All rights reserved.
//

#import "TrainViewController.h"
#import "TimeManager.h"
#import "LFDBManager.h"
#import "TrianDataBaseHandel.h"
#import "CostomManager.h"
#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height
#define degreesToRadians(x) (M_PI*(x)/180.0) //把角度转换成PI的方式
#define PROGREESS_WIDTH (self.view.frame.size.width - 100) //圆直径
#define PROGRESS_LINE_WIDTH 12 //弧线的宽度


static CGFloat verticalSpace1 = 10 ;
static CGFloat verticalSpace2 = 10 ;
static CGFloat verticalSpace3 = 20 ;
@interface TrainViewController ()

@property (nonatomic, strong) CAShapeLayer *trackLayer;
@property (nonatomic, strong) CAShapeLayer *progressLayer;
@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UIButton *clockBtn; // 时钟按钮
@property (nonatomic, strong) UIImageView *cardImage; // 打卡label
@property (nonatomic, strong) UILabel *number3; // 计数label
@property (nonatomic, strong) UIButton *repeatBtn; // 重复按钮 detail
@property (nonatomic, strong) UILabel *detail; // 功能介绍label timeStrLabel
@property (nonatomic, strong) UILabel * timeStrLabel; // 文件“时间”介绍label
@property (nonatomic, strong) UILabel *name; // 课程名label

@property (nonatomic, assign) NSTimeInterval currentTime; // 当前时间
@property (nonatomic, strong) UIButton *start;  // 开始按钮
@property (nonatomic, assign) NSInteger repeatTime; // 重复次数



@property (nonatomic,assign)int useNumber;//使用的次数
@property (nonatomic,strong)NSString * lastTime;//上次使用的时间
@property (nonatomic,assign)int  cycle;//完成的护理数



@end

@implementation TrainViewController

- (void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    [[NSNotificationCenter defaultCenter]postNotificationName:@"supportedInterfaceOrientations" object:self userInfo:@{@"surport" : [NSNumber numberWithBool:NO]}];
    // 模式总时间,自行设定 
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        [[LFDBManager shareManager]updataOrInsertWithName:self.model];

       dispatch_async(dispatch_get_main_queue(), ^{
           //更新页面

       });
    });

    self.currentTime = self.totalTime;
    self.timeLabel.text = [self stringWithTimeInterval:self.totalTime];

}



-(void)viewWillDisappear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = NO;
    
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    //不加这一句,第一次运行tableView的顶端会有大片空白
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    
    //标题
    self.navigationItem.title = @"训练计划";
    
    //view背景颜色
    self.view.backgroundColor = [UIColor whiteColor];
       //重写右按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"课程收藏"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(backToSave)];
    
    
    //美女理疗图片
    UIImageView *cover = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, WIDTH - 20)];
    cover.image = [UIImage imageNamed:@"理疗.jpg"];
    [self.view addSubview:cover];
    
    
    //图片上面的遮罩
    UIView *blackView = [[UIView alloc]init];
    blackView.frame = CGRectMake(0, 0, WIDTH, WIDTH - 20);
    blackView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3];
    [self.view addSubview:blackView];
    
    
    
    
    //丰胸周期
    UILabel *period = [[UILabel alloc]init];
    period.frame = CGRectMake(0, cover.frame.size.height + 30, WIDTH / 3, 20);
    period.text = @"丰胸周期";
    period.textAlignment = NSTextAlignmentCenter;
    period.textColor = [UIColor lightGrayColor];
    [self.view addSubview:period];
    
    //增长值
    UILabel *enhance = [[UILabel alloc]init];
    enhance.frame = CGRectMake(WIDTH / 3, cover.frame.size.height + 30, WIDTH / 3, 20);
    enhance.text = @"增长值";
    enhance.textAlignment = NSTextAlignmentCenter;
    enhance.textColor = [UIColor lightGrayColor];
    [self.view addSubview:enhance];
    
    //使用数
    UILabel *times = [[UILabel alloc]init];
    times.frame = CGRectMake((WIDTH / 3) * 2, cover.frame.size.height + 30, WIDTH / 3, 20);
    times.text = @"使用数";
    times.textAlignment = NSTextAlignmentCenter;
    times.textColor = [UIColor lightGrayColor];
    [self.view addSubview:times];
    
    //天
    UILabel *day = [[UILabel alloc]init];
    day.frame = CGRectMake(WIDTH / 6, cover.frame.size.height + 80, WIDTH / 6, 20);
    day.text = @"天";
    day.textColor = [UIColor darkGrayColor];
    [self.view addSubview:day];
    
    
    //次
    UILabel *count = [[UILabel alloc]init];
    count.frame = CGRectMake((WIDTH / 6) * 5, cover.frame.size.height + 80, WIDTH / 6, 20);
    count.text = @"次";
    count.textColor = [UIColor darkGrayColor];
    [self.view addSubview:count];
    
    UILabel *number1 = [[UILabel alloc]initWithFrame:CGRectMake(0, cover.frame.size.height + 60, WIDTH / 6, 40)];
    number1.textAlignment = NSTextAlignmentRight;
    number1.textColor = [UIColor blackColor];
    number1.text = self.model.period;
    number1.font = [UIFont systemFontOfSize:40];
    [self.view addSubview:number1];
    
    
    UILabel *number2 = [[UILabel alloc]initWithFrame:CGRectMake((WIDTH - 50) / 2 - 10, cover.frame.size.height + 60, WIDTH / 6 +10, 40)];
    number2.textAlignment = NSTextAlignmentCenter;
    number2.textColor = [UIColor blackColor];
    number2.text = self.model.growth;
    number2.font = [UIFont systemFontOfSize:40];
    [self.view addSubview:number2];
    
    self.number3 = [[UILabel alloc]initWithFrame:CGRectMake(4 * (WIDTH / 6), cover.frame.size.height + 60, WIDTH / 6, 40)];
    self.number3.textAlignment = NSTextAlignmentRight;
    self.number3.textColor = [UIColor blackColor];
    self.number3.text = [NSString stringWithFormat:@"%ld", self.model.useNumber ];
    self.number3.font = [UIFont systemFontOfSize:40];
    [self.view addSubview:self.number3];
    
    //横线
    UILabel *line = [[UILabel alloc]initWithFrame:CGRectMake(0, Screen_Height - 100 - 64, WIDTH, 1)];
    line.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:line];
    
    //开始按钮
    UIButton *start = [UIButton buttonWithType:UIButtonTypeCustom];
    start.frame = CGRectMake((WIDTH - 150) / 2, line.frame.origin.y + 20 , 150, 50);
    start.backgroundColor = [UIColor colorWithRed:0.95 green:0.27 blue:0.38 alpha:1];
    [start setTitle:@"开 始" forState:UIControlStateNormal];
    [start setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [start setTitle:@"暂 停" forState:UIControlStateSelected];
    [start addTarget:self action:@selector(startOnClick:) forControlEvents:UIControlEventTouchUpInside];
    start.layer.cornerRadius = 5;
    [self.view addSubview:start];
    
    // 半圆进度条背景图层
    _trackLayer = [CAShapeLayer layer];
    _trackLayer.frame = self.view.bounds;
    [self.view.layer addSublayer:_trackLayer];
    _trackLayer.fillColor = [[UIColor clearColor] CGColor];
    _trackLayer.strokeColor = [[UIColor whiteColor] CGColor];//指定path的渲染颜色
    _trackLayer.opacity = 0.5; //背景
    _trackLayer.lineCap = kCALineCapRound;//指定线的边缘是圆的
    _trackLayer.lineWidth = PROGRESS_LINE_WIDTH;//线的宽度
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.view.center.x, (PROGREESS_WIDTH)/2 + 30 ) radius:(PROGREESS_WIDTH-PROGRESS_LINE_WIDTH)/2 startAngle:degreesToRadians(-210) endAngle:degreesToRadians(30) clockwise:YES];//构建圆形
    _trackLayer.path =[path CGPath]; //把path传递給layer，然后layer会处理相应的渲染，整个逻辑和CoreGraph是一致的。
    
    // 半圆进度条遮罩层
    _progressLayer = [CAShapeLayer layer];
    _progressLayer.frame = self.view.bounds;
    _progressLayer.fillColor =  [[UIColor clearColor] CGColor];
    _progressLayer.strokeColor  = [[UIColor blueColor] CGColor];
    _progressLayer.lineCap = kCALineCapRound;
    _progressLayer.lineWidth = PROGRESS_LINE_WIDTH;
    _progressLayer.path = [path CGPath];
    _progressLayer.strokeEnd = 1;
    
    // 深色
    UIColor *deepColor = [UIColor colorWithRed:225 / 255.0 green:55 / 255.0 blue:82 / 255.0 alpha:1.0];
    // 中间色
    UIColor *middleColor = [UIColor colorWithRed:235 / 255.0 green:123 / 255.0 blue:120 / 255.0 alpha:1.0];
    // 浅色
    UIColor *lightColor = [UIColor colorWithRed:245 / 255.0 green:169 / 255.0 blue:139 / 255.0 alpha:1.0];
    
    CALayer *gradientLayer = [CALayer layer];
    // 左侧渐变图层
    CAGradientLayer *gradientLayer1 =  [CAGradientLayer layer];
    gradientLayer1.frame = CGRectMake(0, 30 , self.view.frame.size.width/2, PROGREESS_WIDTH);
    [gradientLayer1 setColors:[NSArray arrayWithObjects:(id)[deepColor CGColor],(id)[middleColor CGColor], nil]];
    [gradientLayer1 setLocations:@[@0.5,@0.9,@1 ]];
    [gradientLayer1 setStartPoint:CGPointMake(0.5, 1)];
    [gradientLayer1 setEndPoint:CGPointMake(0.5, 0)];
    [gradientLayer addSublayer:gradientLayer1];
    
    // 右侧渐变图层
    CAGradientLayer *gradientLayer2 =  [CAGradientLayer layer];
    [gradientLayer2 setLocations:@[@0.1,@0.5,@1]];
    gradientLayer2.frame = CGRectMake(self.view.frame.size.width/2, 30 , self.view.frame.size.width/2, PROGREESS_WIDTH);
    [gradientLayer2 setColors:[NSArray arrayWithObjects:(id)[middleColor CGColor],(id)[lightColor CGColor], nil]];
    [gradientLayer2 setStartPoint:CGPointMake(0.5, 0)];
    [gradientLayer2 setEndPoint:CGPointMake(0.5, 1)];
    [gradientLayer addSublayer:gradientLayer2];
    
    [gradientLayer setMask:_progressLayer]; //用progressLayer来截取渐变层
    [self.view.layer addSublayer:gradientLayer];
    
    


#pragma mark 参数排版
    // 时间文字label
    self.timeStrLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    _timeStrLabel.center = CGPointMake(self.view.center.x, self.view.center.y /4);
    _timeStrLabel.text = @"时间";
    _timeStrLabel.textColor = [UIColor whiteColor];
    _timeStrLabel.textAlignment = NSTextAlignmentCenter;
    _timeStrLabel.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:_timeStrLabel];
    
    // 时间计数label
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, Screen_Width/3 + 30, 50)];
    self.timeLabel.center = CGPointMake(self.view.center.x, _timeStrLabel.center.y + 30);
    self.timeLabel.text = @"00:00:00";
    self.timeLabel.textColor = [UIColor whiteColor];
    self.timeLabel.textAlignment = NSTextAlignmentCenter;
    self.timeLabel.font = [UIFont systemFontOfSize:35];
    [self.view addSubview:self.timeLabel];
    
    //白条
    UILabel *whiteLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 60, 5)];
    whiteLabel.center = CGPointMake(self.view.center.x, self.timeLabel.frame.origin.y + self.timeLabel.frame.size.height + 10);
    whiteLabel.backgroundColor = [UIColor whiteColor];
    whiteLabel.layer.masksToBounds = YES;
    whiteLabel.layer.cornerRadius = 3;
    [self.view addSubview:whiteLabel];

    //时钟按钮
    self.clockBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.clockBtn.frame = CGRectMake((WIDTH - 30) / 2, whiteLabel.frame.origin.y + 20 , 30, 30);
    [self.clockBtn setBackgroundImage:[UIImage imageNamed:@"clock"] forState:(UIControlStateNormal)];
    [self.clockBtn setBackgroundImage:[UIImage imageNamed:@"clockSelected"] forState:(UIControlStateSelected)];
    [self.clockBtn addTarget:self action:@selector(clockOnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.clockBtn];
    
#define cardWith 60
#define cardheight 20
    

    self.cardImage = [[UIImageView alloc]initWithFrame:CGRectMake((Screen_Width - cardWith)/2, _clockBtn.center.y + 25, cardWith, cardheight)];
    
    self.name = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
    self.name.center = CGPointMake(self.view.center.x, _cardImage.center.y + _cardImage.frame.size.height + verticalSpace1);
    
    self.detail = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 50)];
    _detail.center = CGPointMake(self.view.center.x, _name.center.y + _name.frame.size.height +verticalSpace1 );
    
    //已打卡，默认为未打卡
    
    self.cardImage.image = [UIImage imageNamed:@"请打卡"];
    [self.view addSubview:self.cardImage];
    
    //疗程名称
    
    
    _name.text = self.model.name;
    _name.font = [UIFont boldSystemFontOfSize:20.0f];
    _name.textAlignment = NSTextAlignmentCenter;
    _name.textColor = [UIColor whiteColor];
    [self.view addSubview:_name];

    //功能介绍
   
    _detail.text = self.model.centent;
    _detail.numberOfLines = 0;
    _detail.font = [UIFont systemFontOfSize:15.0f];

    _detail.textAlignment = NSTextAlignmentCenter;
    _detail.textColor = [UIColor whiteColor];
    [self.view addSubview:_detail];
    
    // 循环按钮
    self.repeatBtn = [[UIButton alloc] initWithFrame:CGRectMake(WIDTH - 50, WIDTH - 70, 30, 30)];
    [self.repeatBtn setImage:[UIImage imageNamed:@"once"] forState:UIControlStateNormal];
    [self.repeatBtn setImage:[UIImage imageNamed:@"cycle"] forState:UIControlStateSelected];
    [self.repeatBtn addTarget:self action:@selector(repeatBtnOnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.repeatBtn];
    
#pragma mark 适配
    
    if (Screen_Width == 320 && Screen_Height == 480) {//苹果4
        
        self.name.center = CGPointMake(self.view.center.x, _cardImage.center.y + _cardImage.frame.size.height + verticalSpace1);
        _detail.center = CGPointMake(self.view.center.x, _name.center.y + _name.frame.size.height +verticalSpace1 );
        self.timeLabel.font = [UIFont systemFontOfSize:25];
        _timeStrLabel.font = [UIFont systemFontOfSize:20];

    }else if(Screen_Width == 320 && Screen_Height == 568){//苹果5
        
        self.name.center = CGPointMake(self.view.center.x, _cardImage.center.y + _cardImage.frame.size.height + verticalSpace2);
        _detail.center = CGPointMake(self.view.center.x, _name.center.y + _name.frame.size.height +verticalSpace2 );
        self.timeLabel.font = [UIFont systemFontOfSize:25];
        _timeStrLabel.font = [UIFont systemFontOfSize:20];

    }else{//苹果6
        
        self.name.center = CGPointMake(self.view.center.x, _cardImage.center.y + _cardImage.frame.size.height + verticalSpace3);
        _detail.center = CGPointMake(self.view.center.x, _name.center.y + _name.frame.size.height +verticalSpace3 );
        self.timeLabel.font = [UIFont systemFontOfSize:35];
        _timeStrLabel.font = [UIFont systemFontOfSize:25];

    }
    
}

- (void)repeatBtnOnClick
{
    self.repeatBtn.selected = !self.repeatBtn.selected;
}

-(void)clockOnClick:(UIButton*)sender{
    if (sender.selected) {
    self.cardImage.image = [UIImage imageNamed:@"请打卡"];
    }else{
    self.cardImage.image = [UIImage imageNamed:@"已打卡"];
        [[TrianDataBaseHandel shareManager]insertData:self.model];

    }
  self.clockBtn.selected = !self.clockBtn.selected;

}

- (void) backToLast
{
    
    NSLog(@"返回");
}

- (void) backToSave
{
    
    NSLog(@"收藏");
}

- (NSString *)stringWithTimeInterval:(NSTimeInterval)timeInterval
{
    NSInteger h = timeInterval / 3600;
    NSInteger m = (timeInterval - 3600 * h) / 60;
    NSInteger s = (NSInteger)timeInterval % 60;
    NSString *str = [NSString stringWithFormat:@"%.2ld:%.2ld:%.2ld", (long)h, (long)m ,(long)s];
    return str;
}

// 开始按钮点击方法
- (void)startOnClick:(UIButton *)startBtn
{
    if (startBtn.selected) {
        // 暂停
        [self.timer invalidate];
        self.timer = nil;
    }else{
        // 开始
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(go) userInfo:nil repeats:YES];
    }
    
    startBtn.selected = !startBtn.selected;
}

// 定时器方法
- (void)go
{
    self.currentTime--;
    self.timeLabel.text = [self stringWithTimeInterval:self.currentTime];
    self.progressLayer.strokeEnd = self.currentTime / self.totalTime;
    // 时间归零
    if (0 == self.currentTime) {
        self.repeatTime++;
        // 重复次数增加
        self.currentTime = self.totalTime;
        self.timeLabel.text = [self stringWithTimeInterval:self.currentTime];
        self.number3.text = [NSString stringWithFormat:@"%ld", self.repeatTime];
        self.progressLayer.strokeEnd = 1;
        if(self.repeatBtn.selected)
        {
            // 循环状态
        }else{
            // 单次状态
            self.start.selected = NO;
            [self.timer invalidate];
            self.timer = nil;
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
